package alf.mapping.view.activity;

import alf.common.domain.DomainException;
import alf.mapping.view.Env;
import alf.mapping.view.visuals.EditorEngine;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MapActivity extends Activity implements EditorEngine.EventListener {

	String path= null;//"/mnt/storage/Documents/office1.xml";
	MapView mapView = null;
	EditorEngine editor;
	private static final int SEL_FILE_FOR_LOAD = 1;
	private static final int SEL_FILE_FOR_SAVE = 2;
	private static final int DISPLAY_DIAGRAM = 3;

	private Menu menu;
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		Env.registerActivity(this);
        setContentView(R.layout.map);

		editor = EditorEngine.getInstance();
		editor.registerListener(EditorEngine.Event.ALL,this);
		mapView = (MapView) this.findViewById(R.id.mapView);
		Env.registerStatusView((TextView)this.findViewById(R.id.status));
    }
	
	public void onEvent(EditorEngine.Event e) {
		if (e == EditorEngine.Event.MODE_CHANGED) {
			MenuItem item = this.menu.findItem(R.id.changeMode);
			if (item!=null) {
				item.setIcon(getModeIcon(editor.getMode()));
			} else {
				Env.toast(this,"menu not found");
			}
			checkActionsMenuVisibility();
			this.menu.findItem(R.id.new_item).setVisible(editor.getMode()==EditorEngine.Mode.EDIT);
		} else if (e == EditorEngine.Event.SELECT){
			checkActionsMenuVisibility();
		}
	}

	private void checkActionsMenuVisibility() {
		boolean enabled = !(editor.getSelected() == null) 
			&& editor.getMode()==EditorEngine.Mode.EDIT;
		this.menu.findItem(R.id.m_actions).setVisible(enabled);
	}
	
	@Override 
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent i;
		try {
			switch (item.getItemId()) {
				case R.id.changeMode:
					modeSwitch();
					break;
				case R.id.new_item:
					editor.newItem();
					break;
				case  R.id.copy :
					editor.copy();
					break;
				case R.id.delete:
					editor.delete();
					break;
				case R.id.edit:
					if (editor.getSelected() != null) {
						i = new Intent(this, ItemEditionActivity.class);
						startActivity(i);
					} else {
						Env.setStatus(R.string.msg_map_noedit_non_selected);
					}
					break;
				case R.id.add_link:
					if (editor.getSelected() != null) {
						Env.toast(this, "Select link destination");
						editor.setMode(EditorEngine.Mode.SELECTION);
					} else {
						Env.setStatus(R.string.msg_map_noedit_non_selected);
					}
					break;
				case R.id.m_edit_links:
					if (editor.getSelected()!=null){
						i = new Intent(this,LinkSelectionActivity.class);
						startActivity(i);
					}
					break;
				case R.id.m_item_resize:
					if (editor.getSelected()!=null){
						Env.toast(this,"Use two fingers to resize item");
						editor.setMode(EditorEngine.Mode.RESIZE);
					}
					break;
				case R.id.menu_view_center:
					editor.center();
					break;
				case R.id.zoom_reset : 
					editor.setZoom(100); 
					Env.setStatus(R.string.msg_map_notif_zoom_changed, editor.getZoom());
					break;
				case R.id.diagram_new:
					editor.newDiagram();
					Env.setStatus(R.string.msg_map_notif_diagram_new);
					break;
				case R.id.diagram_display:
					i = new Intent(this, DiagramSelectionActivity.class);
					startActivityForResult(i, DISPLAY_DIAGRAM);
					break;
				case R.id.diagram_edit:
					i = new Intent(this, DiagramEditionActivity.class);
					startActivity(i);
					break;
				case R.id.diagram_delete:
					onDeleteDiagram();
					break;
				case R.id.zoom : 
					editor.setZoom(editor.getZoom() * 2); 
					Env.setStatus(R.string.msg_map_notif_zoom_changed, editor.getZoom());
					break;
				case R.id.unzoom :
					editor.setZoom(editor.getZoom() / 2);
					Env.setStatus(R.string.msg_map_notif_zoom_changed, editor.getZoom());
					break;
				case R.id.status :
					showEditorStatus();
					break;
				case R.id.create_new:
					editor.restore("empty");
					break;
				case R.id.open:
					askForFilename(SEL_FILE_FOR_LOAD);
					break;
				case R.id.save:
					askForFilename(SEL_FILE_FOR_SAVE);
					break;
				case R.id.preferences:
					i = new Intent(this, SettingsActivity.class);
					startActivity(i);
					Env.setStatus(R.string.msg_map_notif_settings_updated);
					break;
				case R.id.help:
					i = new Intent(this, HelpActivity.class);
					i.putExtra(Intent.EXTRA_SUBJECT, "main");
					startActivity(i);
					break;
				default:
					super.onOptionsItemSelected(item);
			}
		} catch (DomainException e) {
			Env.error(e);
			Env.setStatus(R.string.msg_error, e.getMessage());
		}
		return true;
	}

	private void onDeleteDiagram() {
		if (editor.getDiagramNames().length > 1) {
			Dialog.OnClickListener listener = new Dialog.OnClickListener(){
				public void onClick(DialogInterface p1, int p2) {                                
					editor.deleteDiagram();
					Env.setStatus(R.string.msg_map_notif_diagram_deleted);
				}
			};
			Env.confirmDialog(this, "Delete diagram", "Current diagram will be deleted",
							  listener, null);
		} else {
			Env.alertDialog(this, "Warning", "Cannot delete the only diagram left", null);
		}
	}

	private void showEditorStatus() {
		Intent i = new Intent(this, EditorStatusActivity.class);
		startActivity(i);
	}

	private void askForFilename(int operationToPerform) {
		Intent i = new Intent(this, FileSelectionActivity.class);
		if (path==null) {
			path = Env.getDocumentsDir() + "/map.xml";
		}
		i.putExtra(Intent.EXTRA_TEXT, path);
		startActivityForResult(i, operationToPerform);
	}

	public void modeSwitch() {
		EditorEngine.Mode mode = null;
		EditorEngine.Mode currentMode = editor.getMode();
		if (currentMode==EditorEngine.Mode.NAVIGATE) {
			mode = EditorEngine.Mode.EDIT;
		} else if (currentMode==EditorEngine.Mode.EDIT) {
			mode = EditorEngine.Mode.NAVIGATE;
		} else if (currentMode==EditorEngine.Mode.SELECTION) {
			mode = EditorEngine.Mode.EDIT;
		} else if (currentMode==EditorEngine.Mode.RESIZE) {
			mode = EditorEngine.Mode.EDIT;
		}
		editor.setMode(mode);
		Env.setStatus(R.string.msg_map_notif_mode_changed, editor.getMode());
	}
	
	private int getModeIcon(EditorEngine.Mode mode) {
		int menuIcon = -1;
		if (mode.equals(EditorEngine.Mode.EDIT)) {
			menuIcon = R.drawable.m_mode_edit;
		} else if (mode.equals(EditorEngine.Mode.NAVIGATE)) {
			menuIcon = R.drawable.m_mode_nav;
		} else if (mode.equals(EditorEngine.Mode.SELECTION)) {
			menuIcon = R.drawable.m_mode_sel;
		} else if (mode.equals(EditorEngine.Mode.RESIZE)){
			menuIcon = R.drawable.m_mode_resize;
		}
		return menuIcon;
	}

	@Override 
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.map_menu, menu);
		this.menu = menu;
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		try {
			switch (requestCode) {
				case SEL_FILE_FOR_LOAD:
					if (resultCode == Activity.RESULT_OK) {
						path = data.getStringExtra(Intent.EXTRA_RETURN_RESULT);
						Env.setStatus(R.string.msg_map_notif_loading, path);
						editor.restore(path);
						Env.setStatus(R.string.msg_map_notif_loaded, path);
					}
					break;
				case SEL_FILE_FOR_SAVE:
					if (resultCode == Activity.RESULT_OK) {
						path = data.getStringExtra(Intent.EXTRA_RETURN_RESULT);
						if (path != null && !path.equals("")) { 
							Env.setStatus(R.string.msg_map_notif_saving, path);
							editor.save(path);
							Env.setStatus(R.string.msg_map_notif_saved, path);
						} else {
							Env.setStatus(R.string.msg_map_error_empty_path);
						}
					}
					break;
				case DISPLAY_DIAGRAM:
					if (resultCode == Activity.RESULT_OK) {
						int sel = data.getIntExtra(Intent.EXTRA_RETURN_RESULT, 0);  
						editor.displayRoom(sel);
					}
					break;
			}
		} catch (DomainException e) {
			Env.error(e);
			Env.setStatus(R.string.msg_error, e.getMessage());
		}
	}

}
